﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace RsaDemo
{
   public class MD5Sign
    {
	public static string getMd5Sign(IDictionary<string, string> param, string key)
	{
	    param = DictonarySort(param); //排序
	    string signStr = "";
	    foreach (string k in param.Keys)
	    {
		signStr += k + "=" + param[k] + "&";
	    }
	    signStr += "key=" + key;
	    return EncryptionMD5(signStr);
	}

	public static string EncryptionMD5(string str)
	{
	    //MD5加密
	    byte[] result = Encoding.Default.GetBytes(str.Trim());    //tbPass为输入密码的文本框
	    MD5 md5 = new MD5CryptoServiceProvider();
	    byte[] output = md5.ComputeHash(result);
	    return BitConverter.ToString(output).Replace("-", "");
	}

	public static IDictionary<string, string> DictonarySort(IDictionary<string, string> dic)
	{
	    var dicSort = from objDic in dic orderby objDic.Key ascending select objDic;
	    IDictionary<string, string> dcs = new Dictionary<string, string> { };
	    foreach (KeyValuePair<string, string> kvp in dicSort)
	    {
		dcs.Add(kvp.Key, kvp.Value);
	    }
	    return dcs;
	}

	public static string createNoncestr(int length = 32)
	{
	    string chars = "abcdefghijklmnopqrstuvwxyz0123456789";
	    string str = "";
	    Random random = new Random();
	    for (int i = 0; i < length; i++)
	    {
		str += chars.Substring(random.Next(0, chars.Length - 1), 1);
	    }
	    return str;
	}
    }
}
